package ShapeModel;

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

public class CADText extends Rectangle2D.Double implements CADShape {
    private int zVal = 5;
    private Color c = Color.BLACK;
    private float strokeWidth = 1.0f;
    private String text;
    private Font font;
    private double fontHeight;

    public CADText(double x, double y, double w, double h) {
        super(x, y, w, h);
    }

    public CADText(double x, double y, double w, double h, int zVal, Color c, float strokeWidth, String text, Font font) {
        super(x, y, w, h);
        this.zVal = zVal;
        this.c = c;
        this.strokeWidth = strokeWidth;
        this.text = text;
        this.font = font;
        this.fontHeight = h;
    }


    @Override
    public void setZ(int z) {
        this.zVal = z;
    }

    @Override
    public int getZ() {
        return this.zVal;
    }


    private boolean isChineseChar(char c) {
        return String.valueOf(c).matches("[\u4e00-\u9fa5]");
    }

    private double getRatio(){
        double ratio=0;

        for(char c:text.toCharArray()){
            if(isChineseChar(c)) ratio+=1.25;
            else ratio+=0.75;
        }
        return ratio;
    }

    private double getUnit(){
        return fontHeight/1.25;
    }



    @Override
    public void setPos(Point2D p1, Point2D p2) {
        if(p2.getY()<=p1.getY()) return;
        setFont(new Font(Font.MONOSPACED, Font.PLAIN, (int) (p2.getY() - p1.getY())));
        fontHeight = p2.getY() - p1.getY();
        p2.setLocation(p1.getX()+getRatio()*getUnit(),p2.getY());
        this.setFrameFromDiagonal(p1, p2);
    }

    @Override
    public void setColor(Color c) {
        this.c = c;
    }

    @Override
    public Color getColor() {
        return c;
    }

    @Override
    public void setStrokeWidth(float width) {
        this.strokeWidth = width;
    }

    @Override
    public float getStrokeWidth() {
        return strokeWidth;
    }

    @Override
    // 设置正确的resize方法，在两个方向更改大小时，根据比例更改
    public void resize(double dtop, double dbot, double dleft, double dright) {
        Rectangle2D bound = getBounds2D();
        if(dtop==0&&dbot==0){
            if(dleft!=0){
                setPos(bound.getMinX() + dleft, bound.getMinY()+dleft/getRatio(), bound.getMaxX()+dright, bound.getMaxY() + dbot);
            }
            else{
                setPos(bound.getMinX() + dleft, bound.getMinY() + dtop, bound.getMaxX() + dright, bound.getMaxY() + dbot+dright/getRatio());
            }
        }
        else{
            setPos(bound.getMinX() + dleft, bound.getMinY() + dtop, bound.getMaxX() + dright, bound.getMaxY() + dbot);
        }

    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Font getFont() {
        return font;
    }

    public void setFont(Font font) {
        this.font = font;
    }

}